#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <curses.h>
#include <sys/time.h>
#include <string.h>
#include "keyboard.h"
#include "events.h"
#include "debug.h"
#include "libvid.h"


void			quit(p_context				c,
			     int				sig)
{
  int			i;

  if (sig / 10 == 2) /* 20+ : user request */
  {
    pp_exit();

    /* deleting windows */
    if (c != NULL)
      for (i = MAX_WIN; i >= 0; i--)
	if (WIN[i])
	  delwin(WIN[i]);

    nodelay(stdscr, false);
    getch();

    clear();
  }

  if (sig / 10 == 3)
    printf("Window Creation Error\n");

  endwin();

  exit(sig);
}


void			wait_pause(p_context			c)
{
  int			key = 0;

  nodelay(stdscr, false);
  noecho();

  while (key != REQ_PAUSE)
    /* || ((getmouse(&c->mouse) == OK) && */
    /*     (c->mouse.bstate & BUTTON1_CLICKED) && */
    /*     (wenclose(WMENUBAR, c->mouse.y, c->mouse.x)))) */
  {
    if (key == REQ_QUIT)
      quit(c, 20);

    key = getch();
  }
  nodelay(stdscr, true);
}


void			pp_exit(void)
{
  size_t		line, col;

  getmaxyx(stdscr, line, col);

  clear();
  refresh();

  mvwprintw(stdscr, 0, 0, "exiting ncurses <god> mode");
  mvwprintw(stdscr, 1, 0, "thanks for using %s", EXE_NAME);

  /*
  ** grepme QUIT : Insert deadly logo if enough room  :D
  */

  if (col > EXIT_MSG_LEN)
    mvwprintw(stdscr, line - 1, col - EXIT_MSG_LEN, EXIT_MSG);

  refresh();
}


suseconds_t		check_keyboard_state(p_context		c,
					     int		zone,
					     suseconds_t	old,
					     value		ba,
					     struct _video	*video)
{
  int			key;
  suseconds_t		current_usec;
  struct timeval	*current = NULL;
  int			*p;
  int			r;

  p = Data_bigarray_val(ba);

  /* init current time */
  current = malloc(sizeof (struct timeval));
  gettimeofday(current, NULL);
  current_usec = current->tv_usec;

  if (current_usec - old >= TIME_CHECK_KEYBOARD)
  {
    key = getch();
    if (key != ERR)
      if (r = detect_char(c, zone, key, ba, video))
      {
	if (r == REDRAW)
	  p[IBA_UPDATE_WVIDEO] = 1;
	old = current_usec;
      }
  }
  free(current);

  return (old);
}
